#!/bin/bash

#The problem with the following is, that if in the config the
#dir is in quotes like AuthServerDir = "/home/test/testserver"
#the needed command cd $AuthServerDir says that it cant find the
#directory. Thats weird and I have no idea why!
#If I do a cd "/home/test/testserver" in the script it works. o_O
#
#AuthServerDir=$(awk '$1=="AuthServerDir" {print $3}' servermanager.conf)
#WorldServerDir=$(awk '$1=="WorldServerDir" {print $3}' servermanager.conf)
#TestServerDir=$(awk '$1=="TestServerDir" {print $3}' servermanager.conf)
#

#I made a new awk-command to get rid of this error
#The new awk-script searches for " and if there are " it removes all "
#else it just prints the dir

AuthServerDir=$( awk '$1=="AuthServerDir" {
                        if (index($3,"\"") > 0)
                                {gsub("\"","",$3); print $3} \
                        else
                                {print $3}; \
                                next}' servermanager.conf)


WorldServerDir=$( awk '$1=="WorldServerDir" {
                        if (index($3,"\"") > 0)
                                {gsub("\"","",$3); print $3} \
                        else
                                {print $3}; \
                                next}' servermanager.conf)

TestServerDir=$( awk '$1=="TestServerDir" {
                        if (index($3, "\"") > 0)
                                {gsub("\"","",$3); print $3} \
                        else
                                {print $3}; \
                                next}' servermanager.conf)

case $1 in
	authserver)
		./checkStatus observermode authserver
		if [ $? -ne 1 ]; then
			cd $AuthServerDir
			screen -AmdS AuthServer ./authserver
		else
			echo "AuthServer is already running!"
		fi
		
	;;

	worldserver)
		./checkStatus observermode worldserver
		if [ $? -ne 2 ]; then
			cd $WorldServerDir 
			screen -AmdS WorldServer ./worldserver
		else
			echo "WorldServer is already running!"
		fi
	;;

	testserver)
		./checkStatus observermode testserver
		if [ $? -ne 4 ]; then
			cd $TestServerDir
			screen -AmdS TestServer ./worldserver
		else
			echo "TestServer is already running!"
		fi
	;;

esac

